import {
  Controller,
  Post,
  Body,
  Delete,
  HttpCode,
  UseGuards,
  Request,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import prismaClient from '@/config/prismaClient';
import type {
  IBaseQueryApiParams,
  IBaseUser,
  ILoginApiParams,
} from './types/index';
import { UserService } from './user.service';
// import { CreateUserDto } from './dto/create-user.dto';
// import { UpdateUserDto } from './dto/update-user.dto';
// import { ValidatePipe } from './validate/validate.pipe';
import { TokenGuard } from '@/guard/token.guard';
import { parseTokenPayload } from '@/utils/nesjUtils';
import { throwHttpException } from '@/utils/nesjUtils';
import { ErrCode } from '@/types/globalType';
import otherConfig from '@/config/otherConfig';

@Controller('user')
export class UserController {
  constructor(
    private readonly userService: UserService,
    private readonly jwtService: JwtService,
  ) {}

  @Post('create')
  @HttpCode(200)
  async create(@Body() createUserDto: IBaseUser) {
    return await this.userService.create(createUserDto);
  }

  // 登录接口
  @Post('login')
  @HttpCode(200)
  async login(@Body() params: ILoginApiParams) {
    // console.log('params', params);
    const res = await this.userService.login(params);

    return {
      state: '1',
      msg: '登录成功！',
      data: {
        ...res,
        token: this.jwtService.sign({
          ID: res.ID,
          Code: res.Code,
        }),
      },
    };
  }

  // 删除接口
  @Delete('batchDel')
  @UseGuards(TokenGuard)
  @HttpCode(200)
  async batchDelete(@Body() params: { IDs: string }, @Request() req) {
    // 走到这里肯定有 token 并且没过期
    const tokenPayload = parseTokenPayload(
      this,
      req.headers.authorization?.split(' ')[1],
    );

    const res = await this.userService.batchDel(
      params.IDs.split(','),
      tokenPayload,
    );
    if (res == params.IDs.split(',').length) {
      return {
        state: '1',
        msg: '删除成功！',
        data: '',
      };
    } else {
      return {
        state: '0',
        msg: '删除失败！',
        data: '',
      };
    }
  }

  // 更新用户接口
  @Post('update')
  @UseGuards(TokenGuard)
  @HttpCode(200)
  async update(@Body() params: any, @Request() req) {
    // 走到这里肯定有 token 并且没过期
    const tokenPayload = parseTokenPayload(
      this,
      req.headers.authorization?.split(' ')[1],
    );

    const updateCount = await this.userService.update(params, tokenPayload);
    if (updateCount == 0) {
      return {
        state: '0',
        msg: '更新失败！',
      };
    } else {
      return {
        state: '1',
        msg: '更新成功！',
      };
    }
  }

  // 批量查询接口，根据用户ID
  @Post('batchQueryByIDs')
  @UseGuards(TokenGuard)
  @HttpCode(200)
  async batchQueryByIDs(@Body() params: { IDs: string }) {
    const res = await this.userService.batchQueryByIDs(params.IDs.split(','));
    if (res.length == params.IDs.split(',').length) {
      return {
        state: '1',
        msg: '查询成功！',
        data: res,
      };
    } else {
    }
  }

  // 更新用户密码
  @Post('updateUserPassword')
  @UseGuards(TokenGuard)
  @HttpCode(200)
  async updateUserPassword(@Body() params: any, @Request() req) {
    const tokenPayload = parseTokenPayload(
      this,
      req.headers.authorization?.split(' ')[1],
    );

    const res = await this.userService.updateUserPassword(
      params.ID,
      params.Password,
      tokenPayload,
    );

    if (res == 1) {
      return {
        state: '1',
        msg: '修改密码成功！',
        data: '',
      };
    } else {
    }
  }

  // 通用查询接口
  @Post('baseQuery')
  @UseGuards(TokenGuard)
  @HttpCode(200)
  async baseQuery(@Body() params: IBaseQueryApiParams) {
    let sqlWhere = '';
    let sqlOrderby = '';
    let sqlLimit = '';
    console.log('入参', params);
    const defaultParams = ['t1.Code', 't1.Phone']
      .map((f) => {
        return `${f} like '%${params.DefaultInputFilter}%'`;
      })
      .join(' or ');
    try {
      // 处理过滤
      // 基础过滤
      if (params.AdvancedFilterType == '1') {
        if (params.AdvancedFilter.Filters.length == 0) {
          sqlWhere = '';
        } else {
          sqlWhere = ' and ';
          for (
            let index = 0;
            index < params.AdvancedFilter.Filters.length;
            index++
          ) {
            const item = params.AdvancedFilter.Filters[index];

            // 写的不对的话，排除
            if (
              otherConfig.sqlWhereMap.findIndex(
                (f) => f.name == item.Condition,
              ) == -1
            ) {
              continue;
            }
            const sqlWhereMapItem = otherConfig.sqlWhereMap.find(
              (f) => f.name == item.Condition,
            );
            // 基本的比较
            if (
              otherConfig.sqlWhereMap
                .filter((f) => f.type == '1')
                .map((f) => f.name)
                .includes(item.Condition)
            ) {
              sqlWhere += `${item.Field} ${sqlWhereMapItem.symbol} '${item.Value}'`;
            } else if (
              // 包含 和 不包含
              otherConfig.sqlWhereMap
                .filter((f) => f.type == '2')
                .map((f) => f.name)
                .includes(item.Condition)
            ) {
              sqlWhere += `${item.Field} ${sqlWhereMapItem.symbol} '%${item.Value}%'`;
            } else if (
              // in 和 not in
              otherConfig.sqlWhereMap
                .filter((f) => f.type == '3')
                .map((f) => f.name)
                .includes(item.Condition)
            ) {
              sqlWhere += `${item.Field} ${sqlWhereMapItem.symbol} (${item.Value.split(
                ',',
              )
                .map((f) => `'${f}'`)
                .join(',')})`;
            } else if (
              // null 和 is not null
              otherConfig.sqlWhereMap
                .filter((f) => f.type == '4')
                .map((f) => f.name)
                .includes(item.Condition)
            ) {
              sqlWhere += `${item.Field} ${sqlWhereMapItem.symbol}`;
            } else if (
              // 以什么开始
              otherConfig.sqlWhereMap
                .filter((f) => f.type == '5' || f.type == '6')
                .map((f) => f.name)
                .includes(item.Condition)
            ) {
              sqlWhere += `${item.Field} like '${sqlWhereMapItem.type == '5' ? '' : '%'}${item.Value}${sqlWhereMapItem.type == '6' ? '' : '%'}'`;
            } else if (
              // 在什么 到什么之间
              otherConfig.sqlWhereMap
                .filter((f) => f.type == '7')
                .map((f) => f.name)
                .includes(item.Condition)
            ) {
              sqlWhere += `${item.Field} ${sqlWhereMapItem.symbol} '${item.Value[0]}' and '${item.Value[1]}'`;
            }

            if (index + 1 != params.AdvancedFilter.Filters.length) {
              sqlWhere += ' and ';
            }
          }
        }
      }
      // 处理排序
      if (params.AdvancedSort.length != 0) {
        sqlOrderby = 'order by ';
        params.AdvancedSort.forEach((f, i) => {
          sqlOrderby +=
            `${f.Field} ${f.Type}` +
            (i + 1 == params.AdvancedSort.length ? '' : ',');
        });
      }

      // 处理分页

      sqlLimit =
        params.PageSize != 0 && params.PageIndex != 0
          ? `limit ${(params.PageIndex - 1) * params.PageSize},${params.PageSize}`
          : '';

      const res = await prismaClient.$queryRawUnsafe(`
        select 
          t1.ID 't1.ID',
          t1.Code 't1.Code',
          t1.Phone 't1.Phone',
          t1.Email 't1.Email',
          t1.Birthday 't1.Birthday',
          t1.Gender 't1.Gender',
          t1.ProvienceCode 't1.ProvienceCode',
          t1.CityCode 't1.CityCode',
          t1.CountyCode 't1.CountyCode',
          t1.Note 't1.Note',
          t1.Creator 't1.Creator',
          t1.CreateTime 't1.CreateTime',
          t1.LastModifier 't1.LastModifier',
          t1.LastModifyTime 't1.LastModifyTime'
        from base_user t1
        where
          t1.IsDel = '0' and
          (${defaultParams}) ${sqlWhere}
        ${sqlOrderby}
        ${sqlLimit}
      `);
      const res2 = await prismaClient.$queryRawUnsafe(`
            select 
              count(1) 'total'
            from base_user t1
            where
              t1.IsDel = '0' and
              (${defaultParams}) ${sqlWhere}
            ${sqlOrderby} `);

      return {
        state: '1',
        msg: '查询成功！',
        data: {
          data: res,
          total: Number(res2[0].total),
        },
      };
    } catch (error) {
      throwHttpException({
        errCode: ErrCode.CodeError,
        errMsg: '查询失败！',
        errStack: error.message,
      });
    }
  }
}
